/**
 * author: Sheng JIANG
 * date: 2017-04-18
 */

$(function () {

    var $document = $(document);
    var $body = $("body");
    var $template = $(".template");

    var TEMPLATE_SEARCH_TIP = '<div class="nova-tip-form nova-tip-error ifs-error-tip">' +
        '<span class="ifs-error-tip-triangle"></span>' +
        '<span class="nova-icon-xs nova-icon-error"></span>' +
        '<em></em>' +
        '</div>';

    var weekTitle = {
        0: "周日",
        1: "周一",
        2: "周二",
        3: "周三",
        4: "周四",
        5: "周五",
        6: "周六"
    };

    function selectDateCallback() {
        var $input = this.$trigger;
        $input.change();
        var weekText = this.getDayOfWeek();
        $input.siblings("em").html(weekText);
    }

    //单行程日历
    var searchSingletonCal = lv.calendar({
        autoRender: false,
        trigger: ".JS_search_single_date",

        //点击选择日期后的回调函数
        selectDateCallback: selectDateCallback,

        triggerEvent: "focus",
        monthNext: 11,
        dayNext: 364,
        bimonthly: true,
        template: "small",
        cascading: true,
        cascadingMin: 0,
        weekTitle: weekTitle,
        zIndex: 2
    });

    //多行程日历
    var searchMultipleCal = lv.calendar({
        autoRender: false,
        trigger: ".JS_search_multiple_date",

        //点击选择日期后的回调函数
        selectDateCallback: selectDateCallback,

        triggerEvent: "focus",
        bimonthly: true,
        template: "small",
        cascadingMin: 0,
        weekTitle: weekTitle,
        zIndex: 2
    });


    var KEY_CODE = {
        ESC: 27,
        ENTER: 13,
        UP: 38,
        DOWN: 40,
        LEFT: 37,
        RIGHT: 39
    };

    var INPUT_ERROR_STRING = {
        JS_search_city_start: "请选择出发城市",
        JS_search_city_dest: "请选择到达城市",
        JS_search_single_date_start: "请选择出发日期",
        JS_search_single_date_dest: "请选择到达日期",
        JS_search_multiple_date: "请选择出发日期"
    };

    var DUPLICATE_ERROR_TEXT = "抱歉，出发到达城市重复";

    //搜索元素
    var $search = $(".if-search");
    var $searchType = $(".ifs-type");
    var $searchTypeRadio = $searchType.find(".JS_search_type");
    var $searchItems = $(".ifs-bm-items");
    var $searchAddBtn = $(".ifs-bm-add-btn");
    var $searchCity = $(".ifs-search-city");
    var $searchCityTabs = $(".ifs-sc-tabs");
    var $searchCityPanes = $(".ifs-sc-panes");
    var $searchAuto = $(".ifs-search-auto");
    var $searchCityInput = null;
    var cityTemplate = '' +
        '<div class="item item-city" data-city-id="{{type}}|{{cityCode}}|{{airportCode}}|{{text}}">' +
        '<span class="item-name">' +
        '{{name}}' +
        '</span>' +
        '<span class="item-all">' +
        '{{all}}' +
        '</span>' +
        '<span class="item-country">' +
        '{{country}}' +
        '</span>' +
        '<em>' +
        '{{airportCode}}' +
        '</em>' +
        '</div>';
    var planeTemplate = '' +
        '<div class="item item-plane" data-city-id="{{type}}|{{cityCode}}|{{airportCode}}|{{text}}">' +
        '<i>' +
        '</i>' +
        '<span class="item-name">' +
        '{{name}}' +
        '</span>' +
        '<em>' +
        '{{airportCode}}' +
        '</em>' +
        '</div>';
    var cityTemplateTab = '<div class="ifs-sc-tab">{{name}}<i></i></div>';
    var cityTemplateCities = '<div class="ifs-sc-pane">{{cities}}</div>';
    var cityTemplateCity = '<a data-city-id="{{type}}|{{cityCode}}|{{airportCode}}|{{text}}">{{name}}</a>';
    var $searchSwap = $(".ifs-bs-swap");
    var $searchOthersError = $(".ifs-bo-error");

    var $searchOthersAdult = $(".search-others-adult");
    var $searchOthersChild = $(".search-others-child");

    var $searchOthersDropdown = $(".ifs-others-dropdown");

    //出发城市
    var $searchSingletonFromInput = $(".ifs-bs-from .ifs-bs-input");

    //到达城市
    var $searchSingletonToInput = $(".ifs-bs-to .ifs-bs-input");

    //出发日期
    var $searchSingletonFromDate = $(".ifs-bs-from-date .ifs-bs-input");

    //返回日期
    var $searchSingletonToDate = $(".ifs-bs-to-date .ifs-bs-input");

    //搜索单例
    var searchSingleton = {
        /**
         * 初始化
         */
        init: function () {
            this.refreshIndex();
            this.getCity();
            this.firstSelected = {};
            this.updateSearchHeight();
            this.initCalendar();
        },

        initCalendar: function () {
            this.searchCalendar = lv.calendar({
                autoRender: false,
                weekTitle: weekTitle,
                trigger: $("<div></div>")
            });
        },

        render: function () {
            this.readData();
            this.bindEvent();
        },

        getCity: function () {
            var self = this;
            $.ajax({
                // url: "js/city-data.js",
                url: "http://pic.lvmama.com/js/flight/international/city-data.js",
                dataType: "script"
            }).done(function () {
                self.suggestion = jsonpResponse.suggestion;
                self.render();
            }).fail(function (err) {
                console.log(err);
                self.render();
            })
        },

        getSplit: function (str, type) {
            var index = 0;

            var typeTable = {
                "type": 0,
                "cityCode": 1,
                "airportCode": 2,
                "text": 3
            };

            if (type) {
                index = typeTable[type];
            }
            if (str === "" || str === undefined) {
                return "";
            }
            return str.split("|")[index];
        },

        updateSearchHeight: function () {
            var height = $(".if-search").outerHeight();
            var bannerHeight = $(".if-banner").outerHeight();

            var marginTop = height - bannerHeight + 20;
            if (marginTop < 0) {
                marginTop = 0;
            }

            $(".if-sidebar").css("marginTop", marginTop);

        },

        /**
         * 第一次选择单程，复制到多程
         * @param $thisInput
         */
        firstSelect: function ($thisInput) {

            //单程
            if ($thisInput.is(".ifs-bs-input")) {
                var flag = $thisInput.attr("data-flag");
                var $multipleInput = $(".ifs-bm-item").eq(0).find('[data-flag=' + flag + ']');

                //只执行一次
                if (this.firstSelected[flag]) {
                    return false;
                }
                this.firstSelected[flag] = true;

                if ($multipleInput.val() === "") {
                    var singleValue = $thisInput.val();
                    this.copyInputAndId($thisInput, $multipleInput);

                }
            }

        },

        copyInputAndId: function ($src, $dest) {

            $dest.val($src.val());

            var $srcId = $src.siblings(".JS_search_city_id");
            var $destId = $dest.siblings(".JS_search_city_id");

            $destId.val($srcId.val());
            $destId.attr("data-text", $srcId.attr("data-text"));

        },

        /**
         * 移动到下一个输入框
         */
        moveToNextSingletonInput: function ($thisInput) {

            var $inputs;

            //单程
            if ($thisInput.is(".ifs-bs-input")) {
                $inputs = $(".ifs-bs-input");
            }

            if ($thisInput.is(".ifs-bm-input")) {
                var $item = $thisInput.parents(".ifs-bm-item");
                $inputs = $item.find(".ifs-bm-input");
            }

            var index = $inputs.index($thisInput);
            var $nextInput = $inputs.eq(index + 1);

            if ($nextInput.val() === "") {
                setTimeout(function () {
                    $nextInput.focus();
                }, 1)
            }

        },

        /**
         * 保存数据
         */
        saveData: function () {

            var singleData = [
                $(".ifs-bs-from .JS_search_city_id").val() || "",
                $(".ifs-bs-to .JS_search_city_id").val() || "",
                $(".ifs-bs-from-date .JS_search_single_date").val() || "",
                $(".ifs-bs-to-date .JS_search_single_date").val() || ""
            ];

            var multipleDatas = [];

            var $itemList = $(".ifs-bm-items .ifs-bm-item");
            for (var i = 0; i < $itemList.length; i++) {
                var $item = $itemList.eq(i);
                var from = $item.find(".ifs-bm-from .JS_search_city_id").val() || "";
                var to = $item.find(".ifs-bm-to .JS_search_city_id").val() || "";
                var date = $item.find(".JS_search_multiple_date").val() || "";
                var multipleData = [
                    from,
                    to,
                    date
                ];
                multipleDatas.push(multipleData);
            }

            searchData = [
                singleData,
                multipleDatas
            ];

            console.dir(searchData);

            var searchDataStr = JSON.stringify(searchData);
            $.xcookie.setCookie('searchData', searchDataStr, {path: '/', expires: 365});

        },

        refreshCalendarWeek: function ($input) {
            var dateStr = $input.val();
            if (dateStr !== "") {
                var date = lv.calendar.getDateFromFormattedString(dateStr, "yyyy-MM-dd");
                var weekStr = this.searchCalendar.getDayOfWeek(date);
                $input.siblings("em").text(weekStr);
            }
        },

        /**
         * 读取数据
         */
        readData: function () {

            //TODO 测试数据
            var searchData = JSON.parse($.xcookie.getCookie('searchData'));
            if (searchData && searchData[0] && searchData[1]) {

            } else {
                //无缓存
                return false;
            }

            // var searchData = [
            //     [
            //         "5|SHA|SHA|上海（SHA）",
            //         "5|HKG|HKG|香港（HKG）",
            //         "2017-04-25",
            //         "2017-04-25"
            //     ],
            //     [
            //         ["5|SHA|SHA|上海（SHA）", "5|HKG|HKG|香港（HKG）", "2017-04-18"],
            //         ["5|HKG|HKG|香港（HKG）", "5|SHA|SHA|上海（SHA）", "2017-04-18"],
            //         ["5|SHA|SHA|上海（SHA）", "5|HKG|HKG|香港（HKG）", "2017-04-18"]
            //     ]
            // ];

            var $fromId = $(".ifs-bs-from .JS_search_city_id");
            var $toId = $(".ifs-bs-to .JS_search_city_id");
            var $singleFromCity = $(".ifs-bs-from .JS_search_city");
            var $singleToCity = $(".ifs-bs-to .JS_search_city");
            var $singleFromDate = $(".ifs-bs-from-date .JS_search_single_date");
            var $singleToDate = $(".ifs-bs-to-date .JS_search_single_date");

            var singleData = searchData[0];

            var fromText = this.getSplit(singleData[0], "text");
            var toText = this.getSplit(singleData[1], "text");

            $singleFromCity.val(fromText);
            $singleToCity.val(toText);

            $fromId.val(singleData[0]);
            $toId.val(singleData[1]);

            $fromId.attr("data-text", fromText);
            $toId.attr("data-text", toText);

            $singleFromDate.val(singleData[2]);
            $singleToDate.val(singleData[3]);

            this.refreshCalendarWeek($singleFromDate);
            this.refreshCalendarWeek($singleToDate);

            var multipleDatas = searchData[1];
            for (var i = 0; i < multipleDatas.length; i++) {

                //添加行程
                if (i > 1) {
                    this.addMultipleItem();
                }

                var $item = $(".ifs-bm-items .ifs-bm-item").eq(i);

                //填充数据
                var multipleData = multipleDatas[i];
                var from = multipleData[0];
                var to = multipleData[1];
                var date = multipleData[2];
                var $mulFromId = $item.find(".ifs-bm-from .JS_search_city_id");
                var $mulToId = $item.find(".ifs-bm-to .JS_search_city_id");
                var $mulFrom = $item.find(".ifs-bm-from .JS_search_city");
                var $mulTo = $item.find(".ifs-bm-to .JS_search_city");
                var $date = $item.find(".JS_search_multiple_date");

                var mulFromText = this.getSplit(multipleData[0], "text");
                var mulToText = this.getSplit(multipleData[1], "text");

                $mulFrom.val(mulFromText);
                $mulTo.val(mulToText);

                $mulFromId.attr("data-text", mulFromText);
                $mulToId.attr("data-text", mulToText);

                $mulFromId.val(from);
                $mulToId.val(to);
                $date.val(date);

                this.refreshCalendarWeek($date);

            }


        },

        /**
         * 绑定事件
         */
        bindEvent: function () {

            var self = this;


            //TODO 保存xcookie
            $document.on("change", ".if-search-form input[type=text]", function (e) {
                self.saveData();
            });

            $document.on("click change", ".ifs-input-error", function () {
                var $this = $(this);
                var $errorTip = $this.data("error-tip");
                if ($errorTip.length > 0) {
                    $errorTip.remove();
                }
                $this.removeClass("ifs-input-error");
            });

            //出发城市时，默认读取上一程的到达城市
            $document.on("focus", ".JS_search_city_start", function () {
                var $this = $(this);
                var $item = $this.parents(".ifs-bm-item");
                var $prevItem = $item.prev();
                if ($this.val() === "" && $prevItem.length > 0) {
                    self.copyInputAndId($prevItem.find(".JS_search_city_dest"), $this);
                }
            });

            //修改类型
            $searchType.on("change", '[name="SEARCH_TYPE"]', {self: this}, this.searchTypeChangeHandler);

            //添加多程
            $searchAddBtn.on("click", {self: this}, this.searchAddBtnHandler);

            //删除多程
            $searchItems.on("click", ".ifs-bm-close", {self: this}, this.multipleClose);

            //面板tab切换
            $document.on("click", ".ifs-sc-tab", {self: this}, this.cityTabHandler);

            $document.on("focus", ".JS_search_city", {self: this}, this.searchCityClickHandler);
            $document.on("click", ".JS_search_city", {self: this}, function (e) {
                e.stopPropagation();
            });

            $document.on("click", ".JS_search_multiple_date,.JS_search_single_date", function (e) {
                e.stopPropagation();
            });

            $document.on("focus", ".JS_search_multiple_date,.JS_search_single_date", function (e) {
                self.searchCityHide();
                self.searchAutoHide();
            });

            //TODO
            $document.on("keyup", ".JS_search_city", function (e) {
                var $this = $(this);

                switch (e.keyCode) {
                    case KEY_CODE.ENTER:

                        break;
                    case KEY_CODE.UP:

                        break;
                    case KEY_CODE.DOWN:

                        break;
                    default:
                        self.renderAutoCity(true);
                        break;
                }

            });

            $document.on("keydown", ".JS_search_city", function (e) {

                self.inputing = true;

                var $this = $(this);

                switch (e.keyCode) {
                    case KEY_CODE.ESC:
                        $this.blur();
                        self.searchAutoHide();
                        self.searchCityHide();
                        break;
                    case KEY_CODE.ENTER:
                        self.changeCity($searchAuto.find(".item.active"));
                        $this.blur();
                        self.searchAutoHide();
                        self.searchCityHide();
                        break;
                    case KEY_CODE.UP:
                        self.changeAutoActive(-1);
                        e.preventDefault();
                        break;
                    case KEY_CODE.DOWN:
                        self.changeAutoActive(1);
                        e.preventDefault();
                        break;
                    default:
                        break;
                }

            });

            $document.on("blur", ".JS_search_city", function (e) {

                var $this = $(this);
                var text = $this.val();
                var $id = $this.siblings(".JS_search_city_id");
                var id = $id.val();

                self.inputing = false;

                if ($searchAuto.filter(":visible").find(".item").length > 0) {

                    self.changeCity($searchAuto.find(".item.active"));
                } else {

                    if (text === "") {
                        $this.val("");
                        $id.val("");
                        $id.attr("data-text", "");
                    }
                    var newText = $id.attr("data-text");
                    $this.val(newText);
                }


            });

            $searchSwap.on("click", function () {

                self.hideError();

                //value
                var fromVal = $searchSingletonFromInput.val();
                var toVal = $searchSingletonToInput.val();
                $searchSingletonFromInput.val(toVal);
                $searchSingletonToInput.val(fromVal);
                //id
                var $fromId = $searchSingletonFromInput.siblings(".JS_search_city_id");
                var $toId = $searchSingletonToInput.siblings(".JS_search_city_id");

                var fromIdText = $fromId.attr("data-text");
                var toIdText = $toId.attr("data-text");
                if (!toIdText) {
                    toIdText = "";
                }
                if (!fromIdText) {
                    fromIdText = "";
                }
                var fromId = $fromId.val();
                var toId = $toId.val();

                $fromId.attr("data-text", toIdText);
                $toId.attr("data-text", fromIdText);

                $fromId.val(toId);
                $toId.val(fromId);
            });

            //城市名称点击
            $searchCity.on("click", "a", {self: this}, this.searchCityNameClickHandler);

            $document.on("click", ".ifs-search-city", function (e) {
                e.stopPropagation();
            });

            $document.on("click", {self: this}, this.documentClickHandler);

            $document.on("change", ".search-others-adult", function () {
                self.validateOthers();
            });

            $document.on("change", ".search-others-child", function () {
                self.validateOthers();
            });

            $document.on("click", ".ifs-sc-close", function () {
                self.searchCityHide();
            });

            $searchAuto.on("mouseenter", ".item", function () {
                var $this = $(this);
                $this.addClass("active").siblings().removeClass("active");
            });

            $document.on("change", ".ifs-bs-to-date .JS_search_single_date", function () {
                var $this = $(this);
                var val = $this.val();
                if (val !== "") {
                    self.changeReturn();
                }
            });

        },

        changeAutoActive: function (offset) {
            var $item = $searchAuto.find(".item");
            var size = $item.length;
            var $itemActive = $item.filter(".active");
            var indexActive = -1;
            if ($itemActive.length > 0) {
                indexActive = $itemActive.index();
            }
            var $itemNext = null;

            var newIndex = indexActive + offset;

            if (newIndex === size) {
                newIndex = 0;
            }

            if (newIndex === -2) {
                newIndex = size - 1;
            }

            $itemNext = $item.eq(newIndex);

            $itemNext.addClass("active").siblings().removeClass("active");

        },

        changeCity: function ($item) {
            //var text = $item.text();
            var $id = $searchCityInput.siblings(".JS_search_city_id");
            var cityId = $item.attr("data-city-id");
            //var cityIdArray = cityId.split("|");
            var cityName = $item.find(".item-name").text() + "（" + this.getSplit(cityId, "airportCode") + "）";
            $searchCityInput.val(cityName);
            $id.val(cityId);
            $id.attr("data-text", cityName);

            this.moveToNextSingletonInput($searchCityInput);
            this.firstSelect($searchCityInput);

            $searchCityInput.change();

        },

        /**
         * 刷新其他报错
         * return 报错元素
         */
        validateOthers: function () {

            var $adult = $searchOthersAdult;
            var $child = $searchOthersChild;

            var adult = parseInt($adult.val());
            var child = parseInt($child.val());

            if (adult + child > 9) {
                this.showOtherError('乘客总数不能多于<em>9人</em>。');
                return $child;
            } else if (child > adult * 2) {
                this.showOtherError('每名成人最多可携带<em>2名儿童</em>乘机。');
                return $child;
            } else {
                this.showOtherError();
                return null;
            }

        },

        showOtherError: function (text) {
            if (!text) {
                $searchOthersError.hide();
                $search.removeClass("if-search-other-error");
            } else {
                $searchOthersError.find(".ifs-bo-text").html(text);
                $searchOthersError.show();
                $search.addClass("if-search-other-error");
            }

            this.updateSearchHeight();

        },

        /**
         * 显示城市框并切换至第一页
         */
        searchCityShow: function () {
            $searchCity.show();
            $(".ifs-sc-tab").eq(0).addClass("active").siblings().removeClass("active");
            $(".ifs-sc-pane").eq(0).addClass("active").siblings().removeClass("active");
        },

        /**
         * 隐藏城市框
         */
        searchCityHide: function () {
            $searchCity.hide();
        },

        /**
         * 刷新多程编号
         */
        refreshIndex: function () {
            var $itemList = $searchItems.find(".ifs-bm-item");
            var itemSize = $itemList.length;
            for (i = 0; i < itemSize; i++) {
                var $item = $itemList.eq(i);
                $item.find(".ifs-bm-index").text(i + 1);

                $item.find(".ifs-bm-from .JS_search_city").attr("name", "SEARCH_MULTIPLE_FORM_" + i);
                $item.find(".ifs-bm-from .JS_search_city_id").attr("name", "SEARCH_MULTIPLE_FORM_" + i);

                $item.find(".ifs-bm-to .JS_search_city").attr("name", "SEARCH_MULTIPLE_TO_" + i);
                $item.find(".ifs-bm-to .JS_search_city_id").attr("name", "SEARCH_MULTIPLE_TO_" + i);

                $item.find(".ifs-bm-from-date .ifs-bm-input").attr("name", "SEARCH_MULTIPLE_DATE_" + i);

            }
        },

        /**
         * 显示自动完成
         */
        searchAutoShow: function () {
            this.getAutoData();
        },

        /**
         * 获取数据
         */
        getAutoData: function () {
            var self = this;
            $.ajax({
                dataType: "jsonp",
                jsonpCallback: "receive",
                // url: "js/auto-data.json"
                url: "http://pic.lvmama.com/js/flight/international/auto-data.json"
            }).done(function (json) {
                self.renderAutoData(json);
            }).fail(function (err) {
                //console.log(err);
            });
        },

        /**
         * 渲染数据
         */
        renderAutoData: function (json) {
            var data = json.Data;

            var list = [];

            var dataSize = data.length;
            for (var dataIndex = 0; dataIndex < dataSize; dataIndex++) {

                var cityData = data[dataIndex];
                var datas = cityData.Airports;

                list.push(this.renderAutoItemCity(cityData));


                if (!datas) {
                    continue;
                }
                var planeSize = datas.length;


                for (var planeIndex = 0; planeIndex < planeSize; planeIndex++) {
                    var planeData = datas[planeIndex];

                    list.push(this.renderAutoItemPlane(planeData, cityData));
                }
            }

            var html = list.join('');

            if (!data || data.length < 1) {
                html = '<div class="ifs-search-auto-empty">' +
                    '<i class="nova-icon-xs nova-icon-warning"></i>抱歉，暂不支持该地点' +
                    '</div>';
                var width = $searchCityInput.innerWidth();
                $searchAuto.css("width", width);
            } else {
                $searchAuto.css("width", "298px");
            }

            $searchAuto.html(html);
            $searchAuto.find(".item").eq(0).addClass("active").siblings().removeClass("active");
            this.searchAutoItemShow();

        },

        searchAutoItemShow: function () {
            $searchAuto.show();
        },

        searchAutoItemHide: function () {
            $searchAuto.hide();
        },

        renderAutoItemCity: function (cityData) {
            var name = cityData.Name;
            var cityCode = cityData.Code;
            var type = cityData.Type;
            var airportCode = cityData.Code;
            var country = cityData.Country;

            var all = cityData.Airports ? "（所有机场）" : "";

            //隐藏默认国
            if (country === "中国") {
                country = "";
            }

            return this.replaceWith(cityTemplate, {
                name: name,
                all: all,
                cityCode: cityCode,
                type: type,
                airportCode: airportCode,
                country: country,
                text: name + "（" + airportCode + "）"
            });
        },

        renderAutoItemPlane: function (planeData, cityData) {
            var cityName = cityData.Name;
            var name = planeData.Name;
            var cityCode = cityData.Code;
            var airportCode = planeData.Code;
            var type = planeData.Type;

            return this.replaceWith(planeTemplate, {
                name: cityName + name,
                cityCode: cityCode,
                type: type,
                airportCode: airportCode,
                text: cityName + name + "（" + airportCode + "）"
            });
        },

        /**
         * 隐藏自动完成
         */
        searchAutoHide: function () {
            this.searchAutoItemHide();
        },

        /**
         * 替换匹配的内容
         * @param str
         * @param obj
         * @returns {*}
         */
        replaceWith: function (str, obj) {
            for (var i in obj) {
                if (obj.hasOwnProperty(i)) {
                    var reg = new RegExp("\{\{" + i + "\}\}", 'g');
                    str = str.replace(reg, obj[i]);
                }
            }
            return str;
        },

        changeSingle: function () {
            var $input = $(".ifs-bs-to-date .ifs-bs-input");
            var $week = $(".ifs-bs-to-date em");

            $search.removeClass("ifs-is-multiple");
            $searchSingletonToDate.addClass("disabled");
            $(".ifs-bs-to-date").addClass("disabled");

            //saveData
            var dateStr = $input.val();
            var weekStr = $week.text();

            this.singleData = {
                date: dateStr,
                week: weekStr
            };

            //$input.val("");
            //$week.text("");

            searchSingletonCal.options.cascadingNextAuto = false;

        },

        changeReturn: function () {
            var $input = $(".ifs-bs-to-date .ifs-bs-input");
            var $week = $(".ifs-bs-to-date em");

            $(".JS_search_type[value=return]").click();

            $('select[name="SEARCH_TYPE"]').val("return");

            $search.removeClass("ifs-is-multiple");
            $searchSingletonToDate.removeClass("disabled");
            $(".ifs-bs-to-date").removeClass("disabled");

            if (this.singleData) {
                //$input.val(this.singleData.date);
                //$week.text(this.singleData.week);
            }

            searchSingletonCal.options.cascadingNextAuto = true;

        },

        changeMultiple: function () {
            $search.addClass("ifs-is-multiple");
        },

        //事件
        searchTypeChangeHandler: function (e) {
            console.log(111)
            var self = e.data.self;
            var $this = $(this);

            self.hideError();

            //var $checked = $searchTypeRadio.filter(":checked");
            var type = $this.val();

            //var type = $checked.val();
            switch (type) {
                case "single":
                    self.changeSingle();
                    break;
                case "return":
                    self.changeReturn();
                    break;
                case "multiple":
                    self.changeMultiple();
                    break;
                default:
                    throw new Error("未知类型");
                    break;
            }

            self.updateSearchHeight();

        },

        addMultipleItem: function () {
            var $newItem = $template.find(".ifs-bm-item").clone();
            $searchItems.append($newItem);
            var $item = $searchItems.find(".ifs-bm-item");
            var itemSize = $item.length;
            if (itemSize >= 6) {
                $searchAddBtn.hide();
            }
            this.refreshIndex();
            this.updateSearchHeight();
        },

        searchAddBtnHandler: function (e) {
            var self = e.data.self;
            self.addMultipleItem();
        },

        multipleClose: function (e) {

            var self = e.data.self;
            var $item = $(this).parents(".ifs-bm-item");
            $item.remove();
            $searchAddBtn.show();

            self.refreshIndex();
            self.updateSearchHeight();

            //保存
            self.saveData();

        },

        cityTabHandler: function (e) {
            var $this = $(this);
            var index = $this.index();
            $(".ifs-sc-tab").eq(index).addClass("active").siblings().removeClass("active");
            $(".ifs-sc-pane").eq(index).addClass("active").siblings().removeClass("active");

            e.stopPropagation();
        },

        /**
         * 渲染自动补全
         */
        renderAutoCity: function (isAuto) {
            var self = this;

            var text = $searchCityInput.val();

            var left = $searchCityInput.offset().left;
            var top = $searchCityInput.offset().top + $searchCityInput.height();

            var isDest = false;
            if ($searchCityInput.is("[data-flag=JS_search_city_dest]")) {
                isDest = true;
            }

            //多程第二个以及以后开始使用国际作为开始
            if ($searchCityInput.parents(".ifs-bm-item").index() > 0) {
                isDest = true;
            }

            //补全
            if (self.inputing && text !== "") {
                //输入不为空
                self.searchCityHide();
                self.searchAutoShow();

                $searchAuto.css({
                    top: top,
                    left: left
                });

                return false;
            }

            $searchCity.css({
                top: top,
                left: left
            });

            self.renderCity(isDest);
            self.searchCityShow();
            self.searchAutoHide();
        },

        renderCity: function (isDest) {
            var suggestion = this.suggestion;

            var data = {};
            if (!isDest) {
                //开始
                data = suggestion.start;
            } else {
                //到达
                data = suggestion.dest;
            }

            var tabsArr = [];
            var paneArr = [];

            for (var dataIndex = 0; dataIndex < data.length; dataIndex++) {
                var tab = data[dataIndex];

                var tabSegment = this.replaceWith(cityTemplateTab, {
                    name: tab.Name
                });
                tabsArr.push(tabSegment);

                var cities = tab.Cities;

                var citiesArr = [];

                for (var cityIndex = 0; cityIndex < cities.length; cityIndex++) {

                    var city = cities[cityIndex];

                    var citySegment = this.replaceWith(cityTemplateCity, {
                        type: "5",
                        name: city.Name,
                        cityCode: city.Code,
                        airportCode: city.Code,
                        text: city.Name + "（" + city.Code + "）"
                    });

                    citiesArr.push(citySegment)

                }

                var citiesHtml = citiesArr.join("");
                var paneHtml = this.replaceWith(cityTemplateCities, {
                    cities: citiesHtml
                });

                paneArr.push(paneHtml);

            }

            var tabsHtml = tabsArr.join("");
            var panesHtml = paneArr.join("");

            $searchCityTabs.html(tabsHtml);
            $searchCityPanes.html(panesHtml)

        },

        searchCityClickHandler: function (e) {

            var $this = $(this);
            $this.select();

            $('.ui-calendar[data-float="true"]').remove();

            var self = e.data.self;

            //设置最后一次的输入框
            $searchCityInput = $(this);

            //输入为空
            self.renderAutoCity(false);

            e.stopPropagation();
        },

        /**
         * 点击城市链接
         * @param e
         * @returns {boolean}
         */
        searchCityNameClickHandler: function (e) {

            var self = e.data.self;
            if (!$searchCityInput) {
                return false;
            }

            var $this = $(this);
            var $id = $searchCityInput.siblings(".JS_search_city_id");

            var cityId = $this.attr("data-city-id");
            //var cityIdArray = cityId.split("|");
            var cityName = $this.text() + "（" + self.getSplit(cityId, "airportCode") + "）";

            $id.val(cityId);
            $id.attr("data-text", cityName);
            $searchCityInput.val(cityName);
            self.searchCityHide();

            self.firstSelect($searchCityInput);
            self.moveToNextSingletonInput($searchCityInput);

            $searchCityInput.change();

        },

        documentClickHandler: function (e) {
            var self = e.data.self;
            self.searchCityHide();
            self.searchAutoHide();
            $searchOthersDropdown.hide();
        }, hideError: function () {
            $(".ifs-input-error").removeClass("ifs-input-error");
            $(".ifs-error-tip").remove();
        },

        //其他
        searchSubmitValidate: function () {

            this.hideError();

            var ret = false;

            var type = $('[name="SEARCH_TYPE"]').val();
            switch (type) {
                case "single":
                    ret = this.validateSingle();
                    break;
                case "return":
                    ret = this.validateSingle(true);
                    break;
                case "multiple":
                    ret = this.validateMultiple();
                    break;
                default:
                    throw new Error("未知类型");
                    break;
            }

            return ret;

        },

        validateSingle: function (hasReturn) {

            var singleArray = [
                $searchSingletonFromInput,
                $searchSingletonToInput,
                $searchSingletonFromDate
            ];
            if (hasReturn) {
                singleArray.push($searchSingletonToDate);
            }

            var $errorInput = null;

            //验证城市与出发日期
            var singleSize = singleArray.length;
            for (var singleIndex = 0; singleIndex < singleSize; singleIndex++) {
                var $input = singleArray[singleIndex];
                var ret = this.validateInput($input);
                if (ret !== true) {
                    //出错的输入框
                    $errorInput = $input;
                    this.showError($errorInput);
                    return false;
                }
            }

            //单程重复城市验证
            $errorInput = this.validateSingleDuplicateCity();
            if ($errorInput !== null) {
                this.showError($errorInput, DUPLICATE_ERROR_TEXT);
                return false;
            }

            //验证乘客类型
            $errorInput = this.validateOthers();
            if ($errorInput !== null) {
                //this.showError($errorInput);
                return false;
            }

            //验证无问题
            return true;

        },

        setErrorTip: function ($errorTip, errorText) {
            $errorTip.find("em").html(errorText);
        },

        validateSingleDuplicateCity: function () {
            var $fromId = $searchSingletonFromInput.siblings(".JS_search_city_id");
            var $toId = $searchSingletonToInput.siblings(".JS_search_city_id");

            var fromId = this.getSplit($fromId.val(), "cityCode");
            var toId = this.getSplit($toId.val(), "cityCode");

            if (fromId === toId) {
                return $searchSingletonToInput;
            }
            return null;
        },

        showError: function ($errorInput, errorText) {
            $errorInput.addClass("ifs-input-error");
            var $errorTip = $(TEMPLATE_SEARCH_TIP);

            var top = $errorInput.offset().top;
            var left = $errorInput.offset().left;
            var width = $errorInput.outerWidth(true);

            $errorTip.css({
                top: top,
                left: left + width + 8
            });

            var flag = $errorInput.attr("data-flag");

            //默认错误
            if (!errorText) {
                errorText = INPUT_ERROR_STRING[flag];
            }

            this.setErrorTip($errorTip, errorText);

            $errorInput.data("error-tip", $errorTip);

            $body.append($errorTip);

            setTimeout(function () {
                $errorInput.focus();
                $errorInput.select();
            }, 1);

        },

        validateMultiple: function () {

            var $itemList = $searchItems.find(".ifs-bm-item");
            var itemSize = $itemList.length;
            var $errorInput;

            for (var multipleIndex = 0; multipleIndex < itemSize; multipleIndex++) {
                var $item = $itemList.eq(multipleIndex);

                //非空验证
                $errorInput = this.validateItem($item, multipleIndex);
                if ($errorInput !== null) {

                    this.showError($errorInput);

                    //第二程开始
                    var $firstToCity = $(".ifs-bm-item .ifs-bm-to .JS_search_city");
                    if ($errorInput.is(".JS_search_city_start") && $errorInput.parents(".ifs-bm-item").index() === 1 && $firstToCity.val() !== "") {
                        this.copyInputAndId($firstToCity, $errorInput);

                        //闭包
                        (function ($ei) {
                            setTimeout(function () {
                                $ei.focus();
                            }, 1);
                        })($errorInput);

                    }

                    return false;
                }

                //多程重复城市验证
                $errorInput = this.validateMultipleDuplicateCity($item);
                if ($errorInput !== null) {
                    this.showError($errorInput, DUPLICATE_ERROR_TEXT);
                    return false;
                }

            }

            //验证日期
            $errorInput = this.validateMultipleDate();
            if ($errorInput !== null) {

                //this.showError($errorInput, "");
                return false;
            }

            //验证乘客类型
            $errorInput = this.validateOthers();
            if ($errorInput !== null) {
                //this.showError($errorInput);
                return false;
            }

            //验证无问题
            return true;

        },

        //验证日期
        validateMultipleDate: function () {

            var $dateList = $searchItems.find(".JS_search_multiple_date");

            var dateArr = [];
            for (var i = 0; i < $dateList.length; i++) {
                var $date = $dateList.eq(i);
                var $cityStart = $date.parents(".ifs-bm-item").find(".JS_search_city_start");

                //日期与出发城市都不为空的情况下
                if ($date.val() !== "" && $cityStart.val() !== "") {
                    dateArr.push({
                        $date: $date,
                        index: i + 1
                    });
                }

            }

            for (var j = 0; j < dateArr.length - 1; j++) {

                var oldDateObj = dateArr[j];
                var newDateObj = dateArr[j + 1];

                var $oldDate = oldDateObj.$date;
                var $newDate = newDateObj.$date;

                var oldDateIndex = oldDateObj.index;
                var newDateIndex = newDateObj.index;

                var oldDateStr = $oldDate.val();
                var newDateStr = $newDate.val();

                var oldDate = lv.calendar.getDateFromFormattedString(oldDateStr, "yyyy-MM-dd");
                var newDate = lv.calendar.getDateFromFormattedString(newDateStr, "yyyy-MM-dd");

                if (newDate - oldDate < 0) {

                    //抱歉，第2程出发日期不可比第1程早
                    this.showError($newDate, "抱歉，第" + newDateIndex + "程出发日期不可比第" + oldDateIndex + "程早");
                    return $newDate;
                }
            }

            return null;

        },

        validateMultipleDuplicateCity: function ($item) {

            var $from = $item.find(".ifs-bm-from .ifs-bm-input");
            var $to = $item.find(".ifs-bm-to .ifs-bm-input");

            var $fromId = $from.siblings(".JS_search_city_id");
            var $toId = $to.siblings(".JS_search_city_id");

            var fromId = this.getSplit($fromId.val(), "cityCode");
            var toId = this.getSplit($toId.val(), "cityCode");

            if (toId === "") {
                return null;
            }
            if (fromId === toId) {
                return $to;
            }
            return null;
        },

        validateItem: function ($item, index) {
            var $from = $item.find(".ifs-bm-from .ifs-bm-input");
            var $to = $item.find(".ifs-bm-to .ifs-bm-input");
            var $date = $item.find(".ifs-bm-from-date .ifs-bm-input");

            if (this.validateInput($from)) {
                //含出发

                var toRet = this.validateInput($to);

                if (!toRet) {
                    return $to;
                }

                var dateRet = this.validateInput($date);

                if (!dateRet) {
                    return $date;
                }

            } else {
                //不含出发

                //默认2个必填
                if (index < 2) {
                    return $from;
                }
            }

            return null;
        },

        validateInput: function ($input) {
            return this.notEmptyTest($input);
        },

        notEmptyTest: function ($input) {
            return $input.val() !== "";
        }
    };

    searchSingleton.init();

    window.searchSingleton = searchSingleton;

});
